<?php
/**
 * @notes:
 * @return
 * @author: admin
 * @date: 2024/9/11
 */
namespace addons\shopro\service\tokens;

use addons\shopro\service\Wallet;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\tokens\Config;
use app\admin\model\shopro\tokens\Pledgelog;
use app\admin\model\shopro\tokens\Record;
use app\admin\model\shopro\tokens\Pledge;
use app\admin\model\shopro\user\User;
use think\Db;
use think\Exception;

class PledgeService
{

    protected $query = null;
    protected $format = null;

    public function __construct(\Closure $format = null, \think\db\Query $query = null)
    {
        $this->query = $query ?: new Pledge();
        $this->format = $format;
    }

    /***
     * 质押列表
     * @notes:
     * @param $user
     * @param $index
     * @return Trade|null
     * @throws \think\exception\DbException
     * @author: 小谢
     * @date: 2024/9/11 13:47
     */
    public function getList()
    {
        $list = $this->query->select();

        return $list;

    }

    public function pledge($user, $param)
    {
        if ($user->rep_password != md5(md5($param['rep_password']) . $user->salt)) {
            error_stop('支付密码错误！');
        }

        $pledge = $this->query->where('id', $param['id'])->find();
        if (empty($pledge)) {
            error_stop('质押不存在');
        }
        
        if ($user->tokens < $pledge['amount']) {
            error_stop('余额不足');
        }

        Db::startTrans();
        try{
            WalletService::change( $user->id,'tokens',-$pledge['amount'],'token_pledge');
            $plog = new Pledgelog();
            $plog->save([
                'user_id'=>$user->id,
                'pledge_id'=>$pledge['id'],
                'amount'=>$pledge['amount'],
                'day'=>$pledge['day'],
                'rate'=>$pledge['rate'],
                'createtime'=>date("Y-m-d H:i:s",time()),
                'endtime' => date("Y-m-d H:i:s", time() + $pledge['day'] * 86400)
            ]);
            Db::commit();
            return 'ok';
        }catch (\Exception $e){
            Db::rollback();
            error_stop("质押失败");
        }
    }
}